package com.zhangjianling.premp.controller.sys;

import com.zhangjianling.premp.controller.base.BaseController;
import com.zhangjianling.premp.entity.sys.ResultEntity;
import com.zhangjianling.premp.entity.sys.SysDept;
import com.zhangjianling.premp.entity.sys.SysRole;
import com.zhangjianling.premp.entity.sys.SysUser;
import com.zhangjianling.premp.server.sys.BaseInfoService;
import com.zhangjianling.premp.server.sys.SysUserService;
import com.zhangjianling.premp.utils.EncryptionUtil;
import com.zhangjianling.premp.utils.SystemAopLog;
import com.zhangjianling.premp.utils.TimeHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统用户管理
 * 
 * @author zhangjl
 *
 */

@RestController
@RequestMapping("sysUser")
public class SysUserController extends BaseController {
	@Resource
	private SysUserService sysUserService;
	@Resource
	private BaseInfoService baseInfoService;
	/**
	 * 分页用户列表
	 * 
	 * @return
	 */
	@RequiresPermissions("sysUser:pageList")
	@PostMapping("pageList")
	public ResultEntity pageList(
			@RequestParam(value = "pageCurrent", defaultValue = "1") String pageCurrent,
			SysUser user) {
		ResultEntity res = new ResultEntity();
		try {
			Page<SysUser> userPage = sysUserService.pageList(Integer.parseInt(pageCurrent), PAGESIZE,
							"createTime", user);
			if (userPage.getTotalPages() > 0) {
				res.setData(userPage);
				res.setMessage(GET_SUCCESS);
				res.setCode(SUCCESS);
			} else {
				res.setMessage(IS_NULL);
				res.setCode(NULL);
			}
		} catch (SocketException e) {
			e.printStackTrace();
			res.setMessage("网络异常:" + e.getMessage());
			res.setCode(ERROR);
		} catch (Exception e) {
			e.printStackTrace();
			res.setMessage(GET_ERROR + ":" + e.getMessage());
			res.setCode(ERROR);
		}
		return res;
	}

	/**
	 * 保存用户
	 * 
	 * @param user
	 * @return
	 */
	@PostMapping("saveUser")
	@SystemAopLog(description = "用户新增")
	public ResultEntity saveUser(SysUser user, String rolesIds, String sysDeptIds) {
		ResultEntity res = new ResultEntity();
		Subject subject = SecurityUtils.getSubject();
		SysUser currentUser = (SysUser)subject.getPrincipal();
		String curUserName =  currentUser.getUserName();
		String msg = "";
		try {
			if (!StringUtils.isNoneBlank(user.getUserId())) {
				SysUser checkUser = sysUserService.findByUserName(user
						.getUserName());
				if (checkUser != null) {
					res.setMessage("此用户已存在，不能重复添加。");
					res.setCode(ERROR);
					return res;
				}

			}
			if (StringUtils.isNotBlank(rolesIds)) {
				// 设置角色
				String[] arryRole = rolesIds.split(",");
				List<SysRole> rs = new ArrayList<SysRole>();
				for (String roleId : arryRole) {
					SysRole role = new SysRole();
					role.setRoleId(roleId);
					rs.add(role);
				}
				user.setRoles(rs);
			}
			if (StringUtils.isNotEmpty(sysDeptIds)) {
				// 设置部门
				SysDept dept = new SysDept();
				dept.setDeptId(sysDeptIds);
				user.setSysDept(dept);
			}

			if (StringUtils.isNotBlank(user.getUserId())) {
				user.setUpdateTime(TimeHelper.getCurrentTime());
				user.setUpdateUser(curUserName);

			} else {
				user.setCreateTime(TimeHelper.getCurrentTime());
				user.setCreateUser(curUserName);
			}
			user.setIsVisual("1");
			// 用户密码不可逆加密
			user.setPassword(EncryptionUtil.Md5Hash("111111", baseInfoService.getDetail().getSalt()));
			// 用户密码不可逆加密
			// user.setPassword(EncryptionUtil.Md5Hash(user.getPassword(),
			// "gzgyy"));
			// 保存用户
			sysUserService.saveUser(user);
			res.setMessage(OPERATE_SUCCESS);
			res.setCode(SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			msg = e.getMessage();
			res.setMessage(OPERATE_ERROR + ":" + msg);
			res.setCode(ERROR);
		}
		return res;
	}

	/**
	 * 删除用户
	 * 
	 * @return
	 */
	@PostMapping("delUser")
	public ResultEntity delUser(String ID) {
		ResultEntity res = new ResultEntity();
		SysUser sysUser = null;
		String msg = "";
		try {
			sysUser = sysUserService.findUser(ID);
			if (sysUser != null) {
				if(!sysUser.getUserName().equals("admin")){
					sysUserService.deleteUser(ID);
					res.setMessage(DELETE_SUCCESS);
					res.setCode(SUCCESS);
				}else{
					res.setMessage("不能删除超级管理员");
					res.setCode(ERROR);
				}

			} else {
				res.setMessage(DELETE_ERROR);
				res.setCode(ERROR);
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = e.getMessage();
			res.setMessage(DELETE_ERROR + ":" + msg);
			res.setCode(ERROR);
		}
		return res;
	}

	/**
	 * 查询单个用户
	 * 
	 * @return
	 */
	@GetMapping("findUser")
	public ResultEntity findUser(String ID) {
		ResultEntity res = new ResultEntity();
		try {
			res.setData(sysUserService.findUser(ID));
			res.setMessage(GET_SUCCESS);
			res.setCode(SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			res.setMessage(GET_ERROR + ":" + e.getMessage());
			res.setCode(ERROR);
		}
		return res;
	}

	/**
	 * 初始化密码
	 * 
	 * @return
	 */
	@GetMapping("getInitPassword")
	@SystemAopLog(description="初始化密码")
	public ResultEntity getInitPassword(String id) {
		ResultEntity res = new ResultEntity();
		try {
			SysUser sysUser = sysUserService.findUser(id);
			sysUser.setPassword(EncryptionUtil.Md5Hash("111111", baseInfoService.getDetail().getSalt()));
			sysUserService.saveUser(sysUser);
			res.setData(sysUser);
			res.setMessage("密码初始化成功");
			res.setCode(SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			res.setMessage(DELETE_ERROR + ":" + e.getMessage());
			res.setCode(ERROR);
		}
		return res;
	}

	/**
	 * 查询当前用户密码是否正确
	 * @param password
	 * @return
	 */
	@GetMapping("getUser")
	public ResultEntity getUser(String password) {
		ResultEntity res = new ResultEntity();
		try {
			if (StringUtils.isNotBlank(password)) {
				Subject subject = SecurityUtils.getSubject();
				SysUser currentUser = (SysUser)subject.getPrincipal();
				String curUserName =  currentUser.getUserName();
				SysUser sysUser = sysUserService.findUser(curUserName,
						EncryptionUtil.Md5Hash(password, baseInfoService.getDetail().getSalt()));
				if (sysUser == null) {
					res.setMessage(GET_ERROR);
					res.setCode(NULL);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			res.setMessage(GET_ERROR + ":" + e.getMessage());
			res.setCode(ERROR);
		}
		return res;
	}

	/**
	 * 修改密码
	 * 
	 * @param userName
	 * @return
	 */
	@PostMapping("/updatePassword")
	@SystemAopLog(description="修改密码")
	public ResultEntity updatePassword(String password, String password1) {
		ResultEntity res = new ResultEntity();
		try {
			Subject subject = SecurityUtils.getSubject();
			SysUser currentUser = (SysUser)subject.getPrincipal();
			String curUserName =  currentUser.getUserName();
			String md5Password = EncryptionUtil.Md5Hash(password, baseInfoService.getDetail().getSalt());
			String md5Password1 = EncryptionUtil.Md5Hash(password1, baseInfoService.getDetail().getSalt());
			SysUser sysUser = sysUserService.findUser(curUserName,md5Password);
			if (sysUser != null) {
				sysUser.setPassword(md5Password1);
				sysUserService.saveUser(sysUser);
				res.setData(sysUser);
				res.setMessage(UPDATE_SUCCESS);
				res.setCode(SUCCESS);
			} else {
				res.setMessage(UPDATE_ERROR);
				res.setCode(ERROR);
			}

		} catch (Exception e) {
			e.printStackTrace();
			res.setMessage(GET_ERROR + ":" + e.getMessage());
			res.setCode(ERROR);
		}
		return res;
	}

	/**
	 * 检查用户是否已存在
	 * 
	 * @return
	 */
	@GetMapping("checkUser")
	public ResultEntity checkUser(String userName) {
		ResultEntity res = new ResultEntity();
		try {
			res.setData(sysUserService.findByUserName(userName));
			res.setMessage(GET_SUCCESS);
			res.setCode(SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			res.setMessage(GET_ERROR + ":" + e.getMessage());
			res.setCode(ERROR);
		}
		return res;
	}
}
